import arcpy
import string
import os
import sys
reload(sys)
sys.setdefaultencoding('GBK')

try:
    arcpy.AddMessage('-----------start-----------')
    ws=arcpy.GetParameterAsText(0)
    outDir=arcpy.GetParameterAsText(1)
    outCSV=os.path.join(outDir,'data.csv')
    arcpy.env.workspace = ws
    rasters = arcpy.ListRasters("*")
    f = open(outCSV,'a')
    # 表头
    classs=['11','12','13','14','15','21','22','23','24','25','26','31','32','33','41','42','51','52','53','60','71','72','80','90','101','102','120']
    data=['','','','','','','','','','','','','','','','','','','','','','','','','','','']
    header='xzq'
    for n in classs:
        header+=','+n
    header+='\n'
    arcpy.AddMessage(header)
    f.write(header)
    n=0
    for raster in rasters:
        n+=1
        rasloc = ws + os.sep + raster
        # 删除栅格属性表
        arcpy.DeleteRasterAttributeTable_management(raster)
        # 构建栅格属性表
        arcpy.BuildRasterAttributeTable_management(raster, "Overwrite")
        # 获取像元大小
        img_sizeX = arcpy.GetRasterProperties_management(raster,"CELLSIZEX")
        img_sizeY = arcpy.GetRasterProperties_management(raster,"CELLSIZEY")
        strX=str(img_sizeX)
        strX2=strX[0:strX.rfind('.')+3]
        sizeX =float(strX2)
        arcpy.AddMessage('sizeX:'+str(sizeX))
        strY=str(img_sizeY)
        strY2=strY[0:strY.rfind('.')+3]
        sizeY =float(strY2)
        arcpy.AddMessage('sizeY:'+str(sizeY))
        fields = "*"
        try:
            lstFlds = arcpy.ListFields(rasloc)
            if len(lstFlds) == 0:
                break
            
            with arcpy.da.SearchCursor(rasloc, '*') as cursor:
                for row in cursor:
                    #arcpy.AddMessage(row)
                    oid=row[0]
                    val=str(row[1])
                    count=row[2]
                    arcpy.AddMessage('count:'+str(count))
                    area=count*sizeX*sizeY #*0.000001
                    arcpy.AddMessage('area:'+str(area)+'m2')
                    idx=classs.index(val)
                    data[idx]=str(area)
            rowdata=raster
            arcpy.AddMessage(raster)
            rstr=str(raster)
            if raster.endswith('.tif'):
                ridx=raster.rfind(".")
                name=raster[0:ridx]
                arcpy.AddMessage(name)
                rowdata=name
            for d in data:
                rowdata+=','+ d #str(row).replace("(","").replace(")","")
            rowdata+='\n'
            arcpy.AddMessage(rowdata)
            f.write(rowdata)
        except Exception as e:
            print (e)
    del row
    f.close()
    arcpy.AddMessage('All completed:'+str(n))
    arcpy.AddMessage('-----------end-----------')
except arcpy.ExecuteError:
    print arcpy.GetMessages()